package com.gwh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gwh.common.BaseContext;
import com.gwh.entity.ShoppingCart;
import com.gwh.mapper.ShoppingCartMapper;
import com.gwh.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper,ShoppingCart> implements ShoppingCartService {
    @Override
    @Transactional
    public ShoppingCart add(ShoppingCart shoppingCart) {
        //设置用户id,指定当前是哪个用用户在使用
        Long currentId = BaseContext.getCurrentId();
        shoppingCart.setUserId(currentId);

        Long id=shoppingCart.getDishId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,currentId);

        if (id!=null){
            //则是添加菜品
            queryWrapper.eq(ShoppingCart::getDishId,id);
        }else {
            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }

        ShoppingCart cartServiceOne = this.getOne(queryWrapper);
        if (cartServiceOne!=null){
            cartServiceOne.setNumber(cartServiceOne.getNumber()+1);
            this.updateById(cartServiceOne);
        }else {
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            this.save(shoppingCart);
            cartServiceOne=shoppingCart;
        }
        return cartServiceOne;
    }

    @Override
    @Transactional
    public void delete(ShoppingCart shoppingCart) {
        //设置用户id,指定当前是哪个用用户在使用
        Long currentId = BaseContext.getCurrentId();
        shoppingCart.setUserId(currentId);

        Long id=shoppingCart.getDishId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,currentId);

        if (id!=null){
            //则是删除菜品
            queryWrapper.eq(ShoppingCart::getDishId,id);
        }else {
            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }
        ShoppingCart cartServiceOne = this.getOne(queryWrapper);
        if (cartServiceOne.getNumber()>1) {
            cartServiceOne.setNumber(cartServiceOne.getNumber() - 1);
            this.updateById(cartServiceOne);
        }else {
            this.remove(queryWrapper);
        }

    }

    @Override
    @Transactional
    public void clean() {
        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        this.remove(queryWrapper);
    }
}
